package httplib;

import java.io.File;

public class HtmlReader extends HTMLFileHandler {
	
	private String responseHeader = "";
	private byte[] response;
	
	public HtmlReader(){
		//this.writing = new ArrayList<String>();
	}
	
	public String handleFile(String fileName){
		
		try {
			File file = new File(fileName);
			response = getBytesFromFile(file);
			
			String ext = fileName.substring(fileName.lastIndexOf("."));
			
			if (ext.equals(HTTPConstants.HTML_Extension) || (ext.equals(HTTPConstants.TXT_Extension))){
				responseHeader = HTTPConstants.HTTPVersion + " " + HTTPConstants.OK_STATUS 
				+ " " + HTTPConstants.OK_STATUS_MSG + "\n" + HTTPConstants.RESPONSE_HEADER + HTTPConstants.TEXT_HTML_TYPE + "\n" +
				HTTPConstants.CONTENT_LENGTH + Long.toString(file.length()) + "\n\n";
				}
			else if (ext.equals(HTTPConstants.GIF_Extension)) {
				responseHeader = HTTPConstants.HTTPVersion + " " + HTTPConstants.OK_STATUS
				+ " " + HTTPConstants.OK_STATUS_MSG + "\n" + HTTPConstants.RESPONSE_HEADER + HTTPConstants.GIF_TYPE + "\n" + 
				HTTPConstants.CONTENT_LENGTH + Long.toString(file.length()) + "\n\n";
			}
			
			else if (ext.equals(HTTPConstants.JPG_Extension)) {
				responseHeader = HTTPConstants.HTTPVersion + " " + HTTPConstants.OK_STATUS
				+ " " + HTTPConstants.OK_STATUS_MSG + "\n" + HTTPConstants.RESPONSE_HEADER + HTTPConstants.JPG_TYPE + "\n" + 
				HTTPConstants.CONTENT_LENGTH + Long.toString(file.length()) + "\n\n";
			} 
			else if (fileName.equals("forbidden.html")){
				return HTTPConstants.FORBIDDEN_STATUS;
			}
			
			else {
				throw new Exception("File extension not supported.");
			}
		} catch (Exception e){
			//System.out.println(e.getMessage());
			return HTTPConstants.NOT_FOUND_STATUS;
		}
		return HTTPConstants.OK_STATUS;
	}
	
	public String getResponseHeader() {
		return responseHeader;
	}
		
	public byte[] getResponseFile(){
		return response;
	}
}
